package com.koi.common.xxs;

import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author ･ᴗ･
 * @description [XssAndSqlFilter]
 */
// xss：跨站脚本攻击，通过前端input将js脚本注入到后台
// sql注入：将恶意的sql命令注入到后台数据库引擎执行
// csrf：跨站请求伪造，以用户身份在攻击页面对目标网站发起伪造用户操作的请求
// 其中xss和sql注入可以通过拦截请求并进行特殊字符过滤来防御，而csrf需要进行referer检测和token校验进行防御，
// 如果只做了referer检测，在实际的第三方机构检测中，csrf漏洞还是存在的，所以需要进行token校验，token校验在这里不做过多说明，只进行referer检测。
public class XssAndSqlFilter implements Filter {
    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        String method = "GET";
        String param = "";
        XssAndSqlHttpServletRequestWrapper xssRequest = null;
        if (request instanceof HttpServletRequest) {
            method = ((HttpServletRequest) request).getMethod();
            xssRequest = new XssAndSqlHttpServletRequestWrapper((HttpServletRequest) request);
        }
        // auth 字段直接过滤不进行拦截，例如：system:dict:update等带有冒号的auth字段里面的数据。
        String authParam = xssRequest.getParameter("auth");
        if (authParam == null || authParam.isEmpty()) {
            // 如果 auth 参数为空或为特定值，或者是其他您希望允许使用的值，直接通过
            chain.doFilter(xssRequest, response);
            return;
        }
        if ("POST".equalsIgnoreCase(method)) {
            param = getBodyString(xssRequest.getReader());
            if (StringUtils.isNotBlank(param)) {
                if (XssAndSqlHttpServletRequestWrapper.checkXSSAndSql(param)) {
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/json;charset=UTF-8");
                    PrintWriter out = response.getWriter();
                    out.write(JSONObject.toJSONString("您所访问的页面请求中有违反安全规则元素存在，拒绝访问!"));
                    return;
                }
            }
        }
        assert xssRequest != null;
        if (xssRequest.checkParameter()) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.write(JSONObject.toJSONString("您所访问的页面请求中有违反安全规则元素存在，拒绝访问!"));
            return;
        }
        chain.doFilter(xssRequest, response);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

    // 获取request请求body中参数
    public static String getBodyString(BufferedReader br) {
        String inputLine;
        String str = "";
        try {
            while ((inputLine = br.readLine()) != null) {
                str += inputLine;
            }
            br.close();
        } catch (IOException e) {
            System.out.println("IOException: " + e);
        }
        return str;

    }
}
